<template>
  <div class="channel-config-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h1>Payment Channel Weight Configuration</h1>
        <p class="subtitle">Configure the weight, status and amount range of each payment channel. The system will automatically assign recharge channels based on weights</p>
      </div>
      <div class="header-actions">
        <el-button @click="loadConfigs" :loading="loading">
          <el-icon><Refresh /></el-icon>
          Refresh Config
        </el-button>
        <el-button type="danger" @click="handleResetToDefault" :loading="resetting">
          Reset to Default
        </el-button>
        <el-button type="primary" @click="showTestDialog = true">
          <el-icon><DataAnalysis /></el-icon>
          Test Algorithm
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ channelStats.totalChannels }}</div>
          <div class="stat-label">Total Channels</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ channelStats.enabledChannels }}</div>
          <div class="stat-label">Enabled</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ channelStats.configuredChannels }}</div>
          <div class="stat-label">Configured</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ channelStats.totalWeight.toLocaleString() }}</div>
          <div class="stat-label">Total Weight</div>
        </div>
      </el-card>
    </div>

    <!-- 权重分布图 -->
    <el-card class="weight-chart-card">
      <template #header>
        <div class="card-header">
          <el-icon><PieChart /></el-icon>
          <span>Weight Distribution</span>
        </div>
      </template>
      <div class="weight-chart">
        <div v-if="weightChartData.length > 0" class="chart-container">
          <div v-for="item in weightChartData" :key="item.channel" class="weight-item">
            <div class="channel-info">
              <span class="channel-name">{{ item.displayName }}</span>
              <span class="channel-weight">{{ item.weight }}</span>
            </div>
            <div class="progress-bar">
              <el-progress 
                :percentage="item.percentage" 
                :color="item.color"
                :show-text="false"
              />
              <span class="percentage">{{ item.percentage.toFixed(1) }}%</span>
            </div>
          </div>
        </div>
        <el-empty v-else description="No enabled channels" />
      </div>
    </el-card>

    <!-- 渠道配置表格 -->
    <el-card class="config-table-card">
      <template #header>
        <div class="card-header">
          <el-icon><Setting /></el-icon>
          <span>Channel Configuration</span>
          <el-button type="primary" size="small" @click="handleBatchSave" :loading="saving">
            Batch Save
          </el-button>
        </div>
      </template>
      
      <div class="table-container">
        <el-table :data="channelConfigs" style="width: 100%; min-width: 1300px;" v-loading="loading">
        <el-table-column prop="channelId" label="Channel ID" width="100" />
        <el-table-column prop="channelName" label="Channel Name" width="120" />
        <el-table-column prop="displayName" label="Display Name" width="120" />
        
        <el-table-column label="Min Amount" width="140">
          <template #default="{ row }">
            <el-input-number
              v-model="row.minAmount"
              :min="0"
              :max="row.maxAmount"
              size="small"
              controls-position="right"
              @change="markAsChanged(row.channel)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="Max Amount" width="140">
          <template #default="{ row }">
            <el-input-number
              v-model="row.maxAmount"
              :min="row.minAmount"
              :max="999999"
              size="small"
              controls-position="right"
              @change="markAsChanged(row.channel)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="Weight" width="150">
          <template #default="{ row }">
            <div class="weight-input">
              <el-input-number
                v-model="row.weight"
                :min="0"
                :max="999999"
                size="small"
                controls-position="right"
                @change="markAsChanged(row.channel)"
              />
              <el-slider
                v-model="row.weight"
                :min="0"
                :max="10000"
                @change="markAsChanged(row.channel)"
                style="margin-top: 8px;"
              />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="Daily Limit" width="140">
          <template #default="{ row }">
            <el-input-number
              v-model="row.dailyLimit"
              :min="0"
              :max="99999999"
              size="small"
              controls-position="right"
              @change="markAsChanged(row.channel)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="Switch" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.isEnabled"
              @change="markAsChanged(row.channel)"
              :disabled="!row.isConfigured"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="Status" width="200">
          <template #default="{ row }">
            <div class="status-tags">
              <el-tag v-if="row.isConfigured" type="success" size="small">Configured</el-tag>
              <el-tag v-else type="danger" size="small">Not Configured</el-tag>
              <el-tag v-if="row.isEnabled && row.isConfigured" type="primary" size="small">Enabled</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="Actions" width="160">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleSingleSave(row)"
                :loading="row.saving"
                v-if="changedChannels.has(row.channel)"
              >
                Save
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleTestSingle(row)"
                link
              >
                Test
              </el-button>
            </div>
          </template>
        </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 测试对话框 -->
    <el-dialog v-model="showTestDialog" title="Channel Selection Algorithm Test" width="800px">
      <div class="test-form">
        <el-form :model="testForm" label-width="120px">
          <el-form-item label="Test Amount">
            <el-input-number
              v-model="testForm.amount"
              :min="1"
              :max="999999"
              placeholder="Enter test amount"
              style="width: 200px;"
            />
            <span style="margin-left: 10px; color: #909399;">THB</span>
          </el-form-item>
          <el-form-item label="Test Count">
            <el-input-number
              v-model="testForm.testCount"
              :min="10"
              :max="10000"
              placeholder="Enter test count"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="runTest" :loading="testing">Start Test</el-button>
            <el-button @click="runSingleTest" :loading="singleTesting">Single Test</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="testResult" class="test-results">
        <h3>Test Results</h3>
        <div class="result-stats">
          <el-descriptions :column="4" border>
            <el-descriptions-item label="Test Count">{{ testResult.testCount }}</el-descriptions-item>
            <el-descriptions-item label="Test Amount">{{ testResult.amount }} THB</el-descriptions-item>
            <el-descriptions-item label="Total Weight">{{ testResult.totalWeight }}</el-descriptions-item>
            <el-descriptions-item label="Duration">{{ testResult.duration }}ms</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="result-table">
          <el-table :data="testResultTableData" style="width: 100%">
            <el-table-column prop="channel" label="Channel" />
            <el-table-column prop="actualCount" label="Actual Count" />
            <el-table-column prop="actualPercentage" label="Actual %">
              <template #default="{ row }">
                {{ row.actualPercentage }}%
              </template>
            </el-table-column>
            <el-table-column prop="theoreticalPercentage" label="Expected %">
              <template #default="{ row }">
                {{ row.theoreticalPercentage }}%
              </template>
            </el-table-column>
            <el-table-column prop="deviation" label="Deviation">
              <template #default="{ row }">
                <span :class="{ 'positive-deviation': row.deviation > 0, 'negative-deviation': row.deviation < 0 }">
                  {{ row.deviation > 0 ? '+' : '' }}{{ row.deviation }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div v-if="singleTestResult" class="single-test-result">
        <h3>Single Selection Result</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="Selected Channel">{{ singleTestResult.selectedChannel || 'None' }}</el-descriptions-item>
          <el-descriptions-item label="Selection Reason">{{ singleTestResult.reason }}</el-descriptions-item>
          <el-descriptions-item label="Available Channels">{{ singleTestResult.availableChannels.join(', ') }}</el-descriptions-item>
          <el-descriptions-item label="Total Weight">{{ singleTestResult.totalWeight }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, 
  DataAnalysis, 
  PieChart, 
  Setting 
} from '@element-plus/icons-vue'
import { trpc } from '../utils/trpc'

// 响应式数据
const loading = ref(true)
const saving = ref(false)
const resetting = ref(false)
const testing = ref(false)
const singleTesting = ref(false)
const showTestDialog = ref(false)
const changedChannels = ref(new Set<string>())

const channelConfigs = ref<any[]>([])
const channelStats = ref({
  totalChannels: 0,
  enabledChannels: 0,
  configuredChannels: 0,
  totalWeight: 0
})

const testForm = ref({
  amount: 1000,
  testCount: 100
})
const testResult = ref<any>(null)
const singleTestResult = ref<any>(null)

// 权重分布图数据
const weightChartData = computed(() => {
  const enabledChannels = channelConfigs.value.filter(c => c.isEnabled && c.isConfigured)
  const totalWeight = enabledChannels.reduce((sum, c) => sum + c.weight, 0)
  
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  
  return enabledChannels.map((channel, index) => ({
    channel: channel.channel,
    displayName: channel.displayName,
    weight: channel.weight,
    percentage: totalWeight > 0 ? (channel.weight / totalWeight) * 100 : 0,
    color: colors[index % colors.length]
  }))
})

// 测试结果表格数据
const testResultTableData = computed(() => {
  if (!testResult.value) return []
  
  return Object.entries(testResult.value.results).map(([channel, count]) => {
    const actualPercentage = testResult.value.percentages[channel] || 0
    const theoreticalPercentage = testResult.value.theoreticalPercentages?.[channel] || 0
    const deviation = actualPercentage - theoreticalPercentage
    
    return {
      channel,
      actualCount: count,
      actualPercentage: actualPercentage.toFixed(1),
      theoreticalPercentage: theoreticalPercentage.toFixed(1),
      deviation: deviation.toFixed(1)
    }
  })
})

// 标记渠道为已更改
function markAsChanged(channel: string) {
  changedChannels.value.add(channel)
}

// 加载配置
async function loadConfigs() {
  try {
    loading.value = true
    
    // 并行加载配置和统计
    const [configResult, statsResult] = await Promise.all([
      trpc.channelConfig.getChannelConfigs.query(),
      trpc.channelConfig.getChannelStats.query()
    ])
    
    if (configResult.success) {
      channelConfigs.value = configResult.data.channelsWithAvailability.map((channel: any) => ({
        ...channel,
        saving: false
      }))
    }
    
    if (statsResult.success) {
      channelStats.value = statsResult.data
    }
    
    changedChannels.value.clear()
    ElMessage.success('Configuration loaded successfully')
  } catch (error) {
    console.error('Failed to load configs:', error)
    ElMessage.error('Failed to load configuration')
  } finally {
    loading.value = false
  }
}

// 保存单个渠道配置
async function handleSingleSave(row: any) {
  try {
    row.saving = true
    
    const result = await trpc.channelConfig.updateChannelConfig.mutate({
      channel: row.channel,
      config: {
        weight: row.weight,
        isEnabled: row.isEnabled,
        minAmount: row.minAmount,
        maxAmount: row.maxAmount,
        dailyLimit: row.dailyLimit
      }
    })
    
    if (result.success) {
      changedChannels.value.delete(row.channel)
      ElMessage.success(`${row.displayName} configuration saved successfully`)
      
      // 重新加载统计数据
      const statsResult = await trpc.channelConfig.getChannelStats.query()
      if (statsResult.success) {
        channelStats.value = statsResult.data
      }
    } else {
      ElMessage.error(result.message || 'Save failed')
    }
  } catch (error) {
    console.error('Failed to save config:', error)
    ElMessage.error('Failed to save configuration')
  } finally {
    row.saving = false
  }
}

// 批量保存
async function handleBatchSave() {
  if (changedChannels.value.size === 0) {
    ElMessage.warning('No changes to save')
    return
  }
  
  try {
    saving.value = true
    
    const savePromises = Array.from(changedChannels.value).map(channel => {
      const row = channelConfigs.value.find(c => c.channel === channel)
      if (!row) return Promise.resolve()
      
      return trpc.channelConfig.updateChannelConfig.mutate({
        channel: row.channel,
        config: {
          weight: row.weight,
          isEnabled: row.isEnabled,
          minAmount: row.minAmount,
          maxAmount: row.maxAmount,
          dailyLimit: row.dailyLimit
        }
      })
    })
    
    await Promise.all(savePromises)
    
    changedChannels.value.clear()
    ElMessage.success('Batch save successful')
    
    // 重新加载统计数据
    await loadConfigs()
  } catch (error) {
    console.error('Failed to batch save:', error)
    ElMessage.error('Batch save failed')
  } finally {
    saving.value = false
  }
}

// 重置为默认配置
async function handleResetToDefault() {
  try {
    await ElMessageBox.confirm(
      'Are you sure you want to reset to default configuration? This will overwrite all current settings!',
      'Confirm Reset',
      {
        confirmButtonText: 'Reset',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    )
    
    resetting.value = true
    
    const result = await trpc.channelConfig.resetToDefault.mutate()
    
    if (result.success) {
      ElMessage.success('Configuration has been reset to default values')
      await loadConfigs()
    } else {
      ElMessage.error(result.message || 'Reset failed')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to reset config:', error)
      ElMessage.error('Failed to reset configuration')
    }
  } finally {
    resetting.value = false
  }
}

// 运行测试
async function runTest() {
  try {
    testing.value = true
    
    const result = await trpc.channelConfig.testChannelSelection.query({
      amount: testForm.value.amount,
      testCount: testForm.value.testCount
    })
    
    if (result.success) {
      testResult.value = result.data
      singleTestResult.value = null
      ElMessage.success('Test completed')
    } else {
      ElMessage.error(result.message || 'Test failed')
    }
  } catch (error) {
    console.error('Failed to run test:', error)
    ElMessage.error('Test failed')
  } finally {
    testing.value = false
  }
}

// 单次测试
async function runSingleTest() {
  try {
    singleTesting.value = true
    
    const result = await trpc.channelConfig.selectChannel.query({
      amount: testForm.value.amount
    })
    
    if (result.success) {
      singleTestResult.value = result.data
      testResult.value = null
      ElMessage.success('Single test completed')
    } else {
      ElMessage.error(result.message || 'Test failed')
    }
  } catch (error) {
    console.error('Failed to run single test:', error)
    ElMessage.error('Single test failed')
  } finally {
    singleTesting.value = false
  }
}

// 测试单个渠道
function handleTestSingle(row: any) {
  testForm.value.amount = Math.max(row.minAmount, Math.min(row.maxAmount, 1000))
  showTestDialog.value = true
  runSingleTest()
}

// 页面加载时获取配置
onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
.channel-config-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 4px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  text-align: center;
  padding: 8px 0;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.weight-chart-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.weight-chart {
  padding: 16px 0;
}

.chart-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.weight-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.channel-info {
  width: 150px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.channel-name {
  font-weight: 500;
}

.channel-weight {
  color: #909399;
  font-size: 12px;
}

.progress-bar {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.percentage {
  width: 50px;
  text-align: right;
  font-size: 12px;
  color: #606266;
}

.weight-input {
  width: 100%;
}

.status-tags {
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: flex-start;
  min-height: 50px;
  width: 100%;
}

.status-tags .el-tag {
  white-space: nowrap;
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
}

.table-container {
  overflow-x: auto;
  min-height: 300px;
}

.config-table-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.config-table-card .table-container {
  padding: 0;
}

.test-form {
  margin-bottom: 24px;
}

.test-results,
.single-test-result {
  margin-top: 24px;
}

.test-results h3,
.single-test-result h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

.result-stats {
  margin-bottom: 16px;
}

.positive-deviation {
  color: #F56C6C;
}

.negative-deviation {
  color: #67C23A;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .weight-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .channel-info {
    width: 100%;
  }
}
</style>